package com.fjh.shop.orders.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjh.shop.goods.feign.api.GoodsClient;
import com.fjh.shop.goods.model.vo.GoodsListDetailsVO;
import com.fjh.shop.orders.model.entity.Cart;
import com.fjh.shop.orders.model.entity.OrderItem;
import com.fjh.shop.orders.model.vo.CartItemVO;
import com.fjh.shop.orders.service.mapper.OrderItemMapper;
import com.fjh.shop.orders.service.service.OrderItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  订单项服务实现类
 * </p>
 *
 * @author wuyunbin
 * @since 2025-07-16
 */
@Slf4j
@Service
public class OrderItemServiceImpl extends ServiceImpl<OrderItemMapper, OrderItem> implements OrderItemService {

    @Resource
    private GoodsClient goodsClient;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public BigDecimal addOrderItem(List<CartItemVO> cartItemVOS,Long id) {
        ArrayList<OrderItem> orderItems = new ArrayList<>();

        // 汇总价格
        BigDecimal totalAmount = new BigDecimal("0");
        for (CartItemVO item : cartItemVOS) {
            OrderItem orderItem=new OrderItem();
            orderItem.setOrderId(id);
            orderItem.setGoodsId(item.getGoodsId());
            orderItem.setGoodsName(item.getGoodsName());
            orderItem.setGoodsPrice(item.getPrice());
            orderItem.setQuantity(item.getQuantity());
            orderItems.add(orderItem);

            totalAmount = totalAmount.add(item.getPrice().multiply(new BigDecimal(item.getQuantity())));
        }

        this.saveBatch(orderItems);
        
        return totalAmount;
    }

    @Override
    public List<OrderItem> getOrderItemsByOrderId(Long orderId) {
        LambdaQueryWrapper<OrderItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderItem::getOrderId, orderId);
        return this.list(wrapper);
    }

}
